import React, { PureComponent } from 'react';
import ReactDOM from 'react-dom'
import { connect } from 'dva';
import {
  Form, Input, DatePicker, Select, Button, Card, Upload, Radio, Modal, Tooltip,Icon,message,Row,Col,Divider
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './RadioStationAdd.less';
import UploadFile from '../../components/Upload/index';
import AreaTableForm from './AreaTableForm';
import FooterToolbar from '../../components/FooterToolbar';
import docCookies from "../../common/DocCookies";
const FormItem = Form.Item;
const { TextArea } = Input;
const Option = Select.Option;

@connect(state => ({
  radioStation: state.radioStation,
}))
@Form.create()
export default class RadioStationAdd extends PureComponent {
  state = {
    showDetail:false,

    formLoading:false,

    logoFileListDefault:[],
    cardFileListDefault:[],
    businessFileListDefault:[],
    qrcodeFileListDefault:[],

    logoFileList:[],
    cardFileList:[],
    businessFileList:[],
    qrcodeFileList:[],

    submitting:false,

    rsStatusValue:"0",

    radioStationDate:{},

    rsId:docCookies.getItem("rsId"),
    userId:docCookies.getItem("userId"),
    wechatAccountBind:false,

    requires:true,
  };

  componentDidMount  () {
    var self = this;
    const { form , dispatch} = this.props;

    if(self.props.location.query) {
      var rsId = self.props.location.query.rsId;
      var showDetail = self.props.location.query.showDetail;
      if (rsId) {
        if(showDetail){
          self.setState({
            showDetail:showDetail,
          });
        }
        const params = {
          rsId: rsId
        };
        dispatch({
          type: 'radioStation/getRadioStationByRsId',  //请求的action
          payload: params,
          callback: (response) => {
            const curData = response.data;
            console.log(response)
            if(JSON.stringify(curData) == "{}" ){
              return ;
            }
            const  curRsHotlineTel = JSON.parse(curData.rsHotlineTel);
            const rsStatusValue = curData.rsStatus;
            form.setFields({
              rsName : {value: curData.rsName},
              rsDiscription : {value: curData.rsDiscription},
              rsCode : {value: curData.rsCode},
              rsSubordinateUnits : {value: curData.rsSubordinateUnits},
              rsAddress:{value: curData.rsAddress},
              rsAddcurDatas : {value: curData.rsAddcurDatas},
              contacts : {value: curData.contacts},
              contactsTell : {value: curData.contactsTell},
              rsLiveListenUrl : {value: curData.rsLiveListenUrl},
              rsLiveTelecastUrl : {value: curData.rsLiveTelecastUrl},
              accountNumber : {value: curData.accountNumber},
              rsHotlineTel : {value: curRsHotlineTel.length > 0 ? curRsHotlineTel[0].tel : "" },
              rsHotlineTel2 : {value: curRsHotlineTel.length > 1 ? curRsHotlineTel[1].tel : "" },
              rsHotlineTel3 : {value: curRsHotlineTel.length > 2 ? curRsHotlineTel[2].tel : "" },

              username : {value: curData.account},
              newPassword : "",
              confirmPassword : "",
            })
            //设置热线电话类型
            document.getElementById("rsHotlineTelType").value = curRsHotlineTel.length > 0 ? curRsHotlineTel[0].type : "" ;
            document.getElementById("rsHotlineTelType2").value = curRsHotlineTel.length > 1 ? curRsHotlineTel[1].type : "" ;
            document.getElementById("rsHotlineTelType3").value = curRsHotlineTel.length > 2 ? curRsHotlineTel[2].type : "" ;
            // //处理选择状态：
            // self.setState({
            //   rsStatusValue:rsStatusValue+"",
            //   radioStationDate:curData
            // });
            //处理头像
            const  rsLogo = curData.rsLogo;
            const  rsLogoHad = curData.rsLogoHad;
            //处理身份证
            const  cardInfo = JSON.parse(curData.cardInfo);
            const  cardInfoHad = JSON.parse(curData.cardInfoHad);
            //处理营业执照
            const  businessLicenceInfo = JSON.parse(curData.businessLicenceInfo);
            const  businessLicenceInfoHad = JSON.parse(curData.businessLicenceInfoHad);
            //处理二维码
            const  accountQrcodeUrl = curData.accountQrcodeUrl;
            const  accountQrcodeUrlHad = curData.accountQrcodeUrlHad;
            //处理微信公众账号是否绑定
            const  wechatAccountBind = curData.wechatAccountBind == "1" ? true : false;
            // console.log("============="+wechatAccountBind);
            this.setState({
              requires:false,
              rsStatusValue:rsStatusValue+"",
              radioStationDate:curData,
              wechatAccountBind:wechatAccountBind,
              logoFileListDefault:[{
                uid: -1,
                name: '1.png',
                status: 'done',
                url: rsLogo
              }],
              cardFileListDefault:[{
                uid: -1,
                name: '1.png',
                status: 'done',
                url: cardInfo.card1
              },{
                uid: -2,
                name: '2.png',
                status: 'done',
                url: cardInfo.card2
              }],
              businessFileListDefault:[{
                uid: -1,
                name: '1.png',
                status: 'done',
                url: businessLicenceInfo[0].src
              }],
              qrcodeFileListDefault:[{
                uid: -1,
                name: '1.png',
                status: 'done',
                url: accountQrcodeUrl
              }],
              logoFileList:[rsLogoHad],
              cardFileList:[cardInfoHad.card1,cardInfoHad.card2],
              businessFileList:[businessLicenceInfoHad[0].src],
              qrcodeFileList:[accountQrcodeUrlHad],
            });
          }
        });
      }
    }
  }



  /**
   * 点击提交
   * */
  handleSubmit = () => {
    var self = this;
    const { dispatch } = self.props;
    var rsName = "";
    var rsDiscription = "";
    var rsCode = "";
    var rsSubordinateUnits = "";
    var rsAddress = "";
    var contacts = "";
    var contactsTell = "";
    var rsLiveListenUrl = "";
    var rsLiveTelecastUrl = "";
    var accountNumber = "";
    var rsHotlineTelResult = [];

    var rsHotlineTel = "";
    var rsHotlineTel2 = "";
    var rsHotlineTel3 = "";
    var rsHotlineTelType =  "";
    var rsHotlineTelType2 = "";
    var rsHotlineTelType3 = "";

    var username = "";
    var password = "";
    var repassword = "";


    var rsStatus = this.state.rsStatusValue;
    self.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        rsName = fieldsValue.rsName && fieldsValue.rsName.valueOf();
        rsDiscription = fieldsValue.rsDiscription && fieldsValue.rsDiscription.valueOf();
        rsCode = fieldsValue.rsCode && fieldsValue.rsCode.valueOf();
        rsSubordinateUnits = fieldsValue.rsSubordinateUnits && fieldsValue.rsSubordinateUnits.valueOf();
        rsAddress = fieldsValue.rsAddress && fieldsValue.rsAddress.valueOf();
        contacts = fieldsValue.contacts && fieldsValue.contacts.valueOf();
        contactsTell = fieldsValue.contactsTell && fieldsValue.contactsTell.valueOf();
        rsLiveListenUrl = fieldsValue.rsLiveListenUrl && fieldsValue.rsLiveListenUrl.valueOf();
        rsLiveTelecastUrl = fieldsValue.rsLiveTelecastUrl && fieldsValue.rsLiveTelecastUrl.valueOf();
        accountNumber = fieldsValue.accountNumber && fieldsValue.accountNumber.valueOf();
        rsHotlineTel = fieldsValue.rsHotlineTel && fieldsValue.rsHotlineTel.valueOf();
        rsHotlineTel2 = fieldsValue.rsHotlineTel2 && fieldsValue.rsHotlineTel2.valueOf();
        rsHotlineTel3 = fieldsValue.rsHotlineTel3 && fieldsValue.rsHotlineTel3.valueOf();

        username = fieldsValue.username && fieldsValue.username.valueOf();
        password = fieldsValue.newPassword && fieldsValue.newPassword.valueOf();
        repassword = fieldsValue.confirmPassword && fieldsValue.confirmPassword.valueOf();
      }
    });
    rsHotlineTelType =  document.getElementById("rsHotlineTelType").value;
    rsHotlineTelType2 = document.getElementById("rsHotlineTelType2").value;
    rsHotlineTelType3 = document.getElementById("rsHotlineTelType3").value;

    //拼接热线电话字符串
    if(rsHotlineTel != ""){
      var hotLintTel = {"tel": rsHotlineTel,"type": rsHotlineTelType}
      rsHotlineTelResult.push(hotLintTel);
    }
    if(rsHotlineTel2 != ""){
      var hotLintTel2 = {"tel": rsHotlineTel2,"type": rsHotlineTelType2}
      rsHotlineTelResult.push(hotLintTel2);
    }
    if(rsHotlineTel3 != ""){
      var hotLintTel3 = {"tel": rsHotlineTel3,"type": rsHotlineTelType3}
      rsHotlineTelResult.push(hotLintTel3);
    }

    //头像设置 varchar
    const logoFileList = this.state.logoFileList;
    var rsLogo = "";
    if(logoFileList.length <= 0){
      message.info("请上传电台Logo");
      return ;
    }else {
      // console.log(logoFileList[0]);
      rsLogo = logoFileList[0];
    }
    //身份证拼接 jsonb
    const cardFileList = this.state.cardFileList;
    var cardInfo = "";
    if(cardFileList.length <= 1){
      message.info("请上传身份证正反面信息");
      return ;
    }else {
      // console.log(cardFileList[0]);
      cardInfo = {"card1": cardFileList[0],"card2": cardFileList[1]}
    }

    //营业执照 jsonb
    const businessFileList = this.state.businessFileList;
    var businessLicenceInfo = [];
    if(businessFileList.length <= 0){
      message.info("请上传营业执照");
      return ;
    }else {
      for(var index=0;index<businessFileList.length; index++){
        var info = {"src": businessFileList[index]};
        businessLicenceInfo.push(info);
      }
    }
    //微信二维码 varchar
    const qrcodeFileList = this.state.qrcodeFileList;
    var accountQrcodeUrl = "";
    if(qrcodeFileList.length <= 0){
      message.info("请上传微信二维码");
      return ;
    }else {
      accountQrcodeUrl = qrcodeFileList[0];
    }
    var id = null;

    const radioStationDate = this.state.radioStationDate;
    // console.log("submit");
    // console.log(JSON.stringify(radioStationDate));
    if(JSON.stringify(radioStationDate) != "{}"){
      id = radioStationDate.id;
    }
    const params = {
      id:id,
      rsName:rsName,
      rsDiscription:rsDiscription,
      rsCode:rsCode,
      rsSubordinateUnits:rsSubordinateUnits,
      rsAddress:rsAddress,
      contacts:contacts,
      contactsTell:contactsTell,
      rsLiveListenUrl:rsLiveListenUrl,
      rsLiveTelecastUrl:rsLiveTelecastUrl,
      accountNumber:accountNumber,
      rsStatus:rsStatus,
      rsHotlineTel:JSON.stringify(rsHotlineTelResult),
      rsLogo:rsLogo,
      cardInfo:JSON.stringify(cardInfo),
      businessLicenceInfo:JSON.stringify(businessLicenceInfo),
      accountQrcodeUrl:accountQrcodeUrl,
      username:username,
      password:password,
    };
    if(password != repassword) {
      message.info("两次密码输入不一致");
      return;
    }
    if(this.state.requires && !password) {
      message.info("请完善信息");
      return;
    }
    if(rsName || rsDiscription || rsCode || rsSubordinateUnits || rsAddress || contacts || contactsTell || accountNumber || username || rsLiveListenUrl || rsLiveTelecastUrl) {
      dispatch({
        type: 'radioStation/saveOrUpdateRadioStation',  //请求的action
        payload:params,
        callback:(response) =>{
          if(response.errorCode == '1'){
            message.info("添加成功");
            const backDate = response.data;
            // console.log("backData");
            // console.log(backDate);
            this.setState({
              radioStationDate : backDate
            })
          }
        }
      });
    } else {
      message.info("请完善信息");
      return ;
    }

  }

  /**
   * 确定两次密码输入一致
   * */
  handleConfirmPassword = (rule, value, callback) => {
    const { getFieldValue } = this.props.form;
    if (value && value !== getFieldValue('newPassword')) {
      callback('两次输入不一致！')
    }else {
      // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
      callback()
    }
  }
  getLogoImageSrc = (imgSrc) => {
    this.setState({
      logoFileList:imgSrc
    });
  }
  getCardImageSrc = (imgSrc) => {
    this.setState({
      cardFileList:imgSrc
    });
  }
  getBusinessImageSrc = (imgSrc) => {
    this.setState({
      businessFileList:imgSrc
    });
  }
  getQrcodeImageSrc = (imgSrc) => {
    this.setState({
      qrcodeFileList:imgSrc
    });
  }

  handleRsStatusRadioChange = (e) => {
    this.setState({
      rsStatusValue: e.target.value,
    });
  }

  render() {
    // console.log('渲染')
    const {showDetail,formLoading,logoFileListDefault,cardFileListDefault,businessFileListDefault,qrcodeFileListDefault,submitting ,rsStatusValue,radioStationDate,userId,rsId,wechatAccountBind} = this.state;
    // console.log(JSON.stringify(radioStationDate));
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    return (
      <PageHeaderLayout >
        <Card title="基础信息" className={styles.card} bordered={false}>
          <Form
            style={{ marginTop: 8 }}
          >
            <FormItem
              {...formItemLayout}
              label="电台Logo"
            >
              {showDetail?
                ( logoFileListDefault.length == 1 ? <img alt="example"  src={logoFileListDefault[0].url} style={{width:100,height:100}} />: "" )
                :
                <UploadFile
                  maxFileCount = {1}
                  defaultList={logoFileListDefault}
                  getImgSrc={(imgSrc)=> this.getLogoImageSrc(imgSrc)}
                  buttonName = "Logo上传"
                  acceptName = 'image/*'
                  suffixDefault = {['jpg','png']}
                  data={{
                    userId:userId,
                  }}
                />
              }
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="电台名称"
            >
              {getFieldDecorator('rsName', {
                rules: [{
                  required: true, message: '请输入电台名称',
                }],
              })(
                <Input placeholder="请输入电台名称"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="电台描述"
            >
              {getFieldDecorator('rsDiscription', {
                rules: [{
                  required: true, message: '请输入电台描述',
                }],
              })(
                <Input placeholder="请输入电台描述"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="电台编码"
            >
              {getFieldDecorator('rsCode', {
                rules: [{
                  required: true, message: '请输入电台编码',
                }],
              })(
                <Input placeholder="请输入电台编码"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="所属单位"
            >
              {getFieldDecorator('rsSubordinateUnits', {
                rules: [{
                  required: true, message: '请输入所属单位',
                }],
              })(
                <Input placeholder="请输入所属单位"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="电台地址"
            >
              {getFieldDecorator('rsAddress', {
                rules: [{
                  required: true, message: '请输入电台地址',
                }],
              })(
                <Input placeholder="请输入电台地址"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系人"
            >
              {getFieldDecorator('contacts', {
                rules: [{
                  required: true, message: '请输入联系人',
                }],
              })(
                <Input placeholder="请输入联系人"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="联系电话"
            >
              {getFieldDecorator('contactsTell', {
                rules: [{
                  required: true, message: '请输入联系电话',
                }],
              })(
                <Input placeholder="请输入联系电话"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="身份证正反面"
            >
              {showDetail ?
                ( cardFileListDefault.length == 2 ?
                <div>
                  <img alt="example"  src={cardFileListDefault[0].url} style={{width:100,height:100}}/>
                  <img alt="example"  src={cardFileListDefault[1].url} style={{width:100,height:100}}/>
                </div> : "" )
                :
              <UploadFile
                maxFileCount = {2}
                defaultList={cardFileListDefault}
                getImgSrc={(imgSrc)=> this.getCardImageSrc(imgSrc)}
                buttonName = "身份证正反面"
                acceptName = 'image/*'
                suffixDefault = {['jpg','png']}
                data={{
                  userId:1,
                  filePath:'test/photo/'}}
              />
              }
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="营业执照"
            >
              {showDetail?
                ( businessFileListDefault.length == 1 ? <img alt="example"  src={businessFileListDefault[0].url} style={{width:100,height:100}}/> : "")
                :
                <UploadFile
                  maxFileCount = {1}
                  defaultList={businessFileListDefault}
                  getImgSrc={(imgSrc)=> this.getBusinessImageSrc(imgSrc)}
                  buttonName = "营业执照"
                  acceptName = 'image/*'
                  suffixDefault = {['jpg']}
                  data={{
                    userId:1,
                    filePath:'test/photo/'}}
                />
              }
            </FormItem>
          </Form>
        </Card>
        <Card title="管理员账号" className={styles.card} bordered={false}>
          <Form autoComplete="off">
            <FormItem
              {...formItemLayout}
              label="账号"
            >
              {getFieldDecorator('username', {
                rules: [{
                  required: true, message: '请输入账号',
                }],
              })(
                <Input placeholder="请输入账号" disabled={showDetail} />

              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="密码"
            >
              {getFieldDecorator('newPassword', {
                rules: [{
                  required: this.state.requires, message: '请输入密码',
                }],
              })(
                <Input placeholder="请输入密码" type="password" disabled={showDetail} />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="确认密码"
            >
              {getFieldDecorator('confirmPassword', {
                rules: [{
                  required: this.state.requires,
                  message: '密码不一致',
                  validator: this.handleConfirmPassword
                }],
              })(
                <Input placeholder="请输入确认密码" type="password" disabled={showDetail} autoComplete="new-password" />
              )}
            </FormItem>
          </Form>
        </Card>

        <Card title="微信授权" className={styles.card} bordered={false}>
          <div style={{textAlign:"center"}}>
            {wechatAccountBind == true ? "绑定成功" : (JSON.stringify(radioStationDate) == "{}" ? "请先创建当前电台信息":  <a href={"http://fm.umakr.cn/api/web/wechat/wechatopen/goAuthor/"+radioStationDate.id} target="_blank">点击微信授权</a> )}
          </div>
        </Card>

        <Card title="电台服务" className={styles.card} bordered={false}>
          <Form >
            <FormItem
              {...formItemLayout}
              label="在线收听地址"
            >
              {getFieldDecorator('rsLiveListenUrl', {
                rules: [{
                  required: true, message: '请输入在线收听地址',
                }],
              })(
                <Input placeholder="请输入在线收听地址"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="视频直播地址"
            >
              {getFieldDecorator('rsLiveTelecastUrl', {
                rules: [{
                  required: true, message: '请输入视频直播地址',
                }],
              })(
                <Input placeholder="请输入视频直播地址"  disabled={showDetail}  />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="微信公众号"
            >
              {getFieldDecorator('accountNumber', {
                rules: [{
                  required: true, message: '请输入微信公众号',
                }],
              })(
                <Input placeholder="请输入微信公众号"  disabled={showDetail}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="微信二维码"
            >
              {showDetail?
                ( qrcodeFileListDefault.length == 1 ? <img alt="example"  src={qrcodeFileListDefault[0].url} style={{width:100,height:100}}/> : "" )
                :
                <UploadFile
                  maxFileCount = {1}
                  defaultList={qrcodeFileListDefault}
                  getImgSrc={(imgSrc)=> this.getQrcodeImageSrc(imgSrc)}
                  buttonName = "照片上传"
                  acceptName = 'image/*'
                  suffixDefault = {['jpg','png']}
                  data={{
                    userId:1,
                    filePath:'test/photo/'}}
                />
              }
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="热线1"
            >
              <div>
                <div  style={{float:'left'}}>
                  {getFieldDecorator('rsHotlineTel')(
                    <Input placeholder="请输入热线1"  disabled={showDetail} />
                  )}
                </div>
                <div  style={{float:'left',marginLeft:5}}>
                  <Input placeholder="请输类型"  disabled={showDetail} id="rsHotlineTelType" />
                </div>
              </div>
            </FormItem>

            <FormItem
            {...formItemLayout}
            label="热线2"
           >
              <div>
                <div  style={{float:'left'}}>
                  {getFieldDecorator('rsHotlineTel2')(
                    <Input placeholder="请输入热线2"  disabled={showDetail} />
                  )}
                </div>
                <div  style={{float:'left',marginLeft:5}}>
                    <Input placeholder="请输类型"  disabled={showDetail} id="rsHotlineTelType2"  />
                </div>
              </div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="热线3"
            >
              <div>
                <div  style={{float:'left'}}>
                  {getFieldDecorator('rsHotlineTel3')(
                    <Input placeholder="请输入热线3"  disabled={showDetail} />
                  )}
                </div>
                <div  style={{float:'left',marginLeft:5}}>
                    <Input placeholder="请输类型"  disabled={showDetail} id="rsHotlineTelType3" />
                </div>
              </div>
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="状态"
            >
              {getFieldDecorator('rsStatus', {
                initialValue: rsStatusValue,
              })(
                <Radio.Group onChange={this.handleRsStatusRadioChange} disabled={showDetail} >
                  <Radio value="0">未开通</Radio>
                  <Radio value="1">正常</Radio>
                  <Radio value="2">冻结</Radio>
                  <Radio value="3">删除</Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Form>
        </Card>
        <Card title="电台频率" className={styles.card} bordered={false}>
          <AreaTableForm
            rsId={JSON.stringify(radioStationDate) == "{}" ?  "" :radioStationDate.id}
          />
        </Card>
        <FooterToolbar style={{ width: this.state.width }}>
          <Button type="success" onClick={(e) => this.handleSubmit()} loading={submitting}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderLayout>
    );
  }
}
